package ThreadPool.chapter3;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

/**
 * @author oyz
 * @version 1.0.4
 * @description:  jdbc连接池对象的仿写
 * @date 2022/12/21 21:19
 */
public class Pool<T> {
    // 标识默认端的大小
    private final int size;

    //存放对象的池子
    private final List<T> list = new ArrayList<>();

    // 检出标志
    private final boolean[] flags;

    //定义一个信号量
    private final Semaphore semaphore;


    public Pool(Class<T> clazz, int size){
        this.size = size;
        flags = new boolean[size];
        semaphore = new Semaphore(size,true);
        for (int i = 0; i < size; i++) {
            try {
                list.add(clazz.newInstance());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    public T check(){
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return getItem();
    }


    public synchronized T getItem(){
        for (int i = 0; i < size; i++) {
            if(!flags[i]){
                flags[i] = true;
                return list.get(i);
            }
        }
        return null;
    }

    public void checkIn(T t){
        if(relaseItem(t)){
            // 释放许可，让其他线程可以操作
            semaphore.release();
        }
    }

    public synchronized boolean relaseItem(T iteam){
        int i = list.indexOf(iteam);
        if(i == -1){
            return false;
        }
        if(flags[i]){
            flags[i] = false;
            return true;
        }
        return false;
    }


}
